package com.example.doer.reading.AppActivities;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.ab.activity.AbActivity;
import com.ab.http.AbHttpUtil;
import com.ab.http.AbStringHttpResponseListener;
import com.ab.image.AbImageLoader;
import com.example.doer.reading.AppDataModel.CircleImageView;
import com.example.doer.reading.AppDataModel.ThemeNameToLogo;
import com.example.doer.reading.AppDataModel.Topic;
import com.example.doer.reading.AppDataModel.TopicReply;
import com.example.doer.reading.R;
import com.example.doer.reading.global.MyApplication;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.ab.util.AbToastUtil.showToast;

/**
 * Created by 严旭江 on 2017/7/23.
 */

public class SearchResultActivity extends AbActivity {
    AbHttpUtil abHttpUtil;
    static String searchKey;
    SearchResultAdapter resultAdapter = null;
    ListView searchListView;
    Button returnBtn;
    List<Topic>topicList = new ArrayList<Topic>();
    AbImageLoader abImageLoader;

    @Override
    public void onCreate(Bundle savedInstancetype){
        super.onCreate(savedInstancetype);
        setAbContentView(R.layout.activity_search);
        abHttpUtil = AbHttpUtil.getInstance(SearchResultActivity.this);
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        searchListView = (ListView) findViewById(R.id.searListView);
        returnBtn = (Button)findViewById(R.id.SearchActivirty_btnReturn);
        abImageLoader = AbImageLoader.getInstance(SearchResultActivity.this);
        /**
         * 获取传送的搜索关键字
         */
        searchKey = bundle.getString("searchKey");
        /**
         * 全局获取UserID
         */
        String UserID = MyApplication.user.getUserID();
        String url = "http://192.168.191.1/Reading/QuestionServlet?Action=search&userID="+UserID+"&para="+searchKey;
        abHttpUtil.get(url, new AbStringHttpResponseListener() {
            @Override
            public void onSuccess(int i, String s) {
                Topic addTopic;
                TopicReply addTopicReply;
                try {
                    JSONArray jsonArray = new JSONObject(s).getJSONArray("search");
                    for(int j = 0;j<jsonArray.length();j++){
                        JSONObject jsonObject = (JSONObject)jsonArray.get(j);
                        //Theme名字  一级
                        String themeName = jsonObject.getString("QuestionFromTopicName");
                        String themeLogoPath = jsonObject.getString("topic_logo");
                        //问题名字   二级
                        String topicName = jsonObject.getString("QuestTitle");
                        String topicID = jsonObject.getString("QuestID");
                        String topicDesc = jsonObject.getString("QuestDescription");
                        String topicFavourCount = jsonObject.getString("QuestionFocusCount");
                        String topicCollectCount = jsonObject.getString("QuestionAnswerCount");
                        if (!jsonObject.isNull("answer")) {
                            JSONObject thirdObj = (JSONObject) jsonObject.get("answer");
                            String thirdObjID = thirdObj.getString("AnswerID");
                            String thirdObjFromTopicID = thirdObj.getString("AnswerFromQuestID");
                            String thirdObjContent = thirdObj.getString("AnswerContent");
                            String thirdObjUserName = thirdObj.getString("AnswerFromUserName");
                            String thirdObjUserID = thirdObj.getString("AnswerFromUserID");
                            String thirdObjFavourCount = thirdObj.getString("ThumbUpCount");
                            String thirdObjReplyCount = thirdObj.getString("ReplyCount");
                            String thirdObjCollectCount = thirdObj.getString("UserCollectCount");
                            boolean thirdObjIsThumbUp = thirdObj.getBoolean("IsThumbUp");
                            boolean thirdObjIsCollect = thirdObj.getBoolean("IsCollect");
                            addTopicReply = new TopicReply(thirdObjID,thirdObjFromTopicID,thirdObjUserID,thirdObjUserName,thirdObjContent,Integer.valueOf(thirdObjFavourCount),Integer.valueOf(thirdObjCollectCount),Integer.valueOf(thirdObjReplyCount),thirdObjIsThumbUp,thirdObjIsCollect);
                            addTopic = new Topic(topicID,themeName,themeLogoPath,topicName,topicDesc,Integer.valueOf(topicCollectCount),Integer.valueOf(topicFavourCount),addTopicReply);
                            topicList.add(addTopic);
                        }
                        else {
                            //说明问题没有回答
                            addTopic = new Topic(topicID,themeName,themeLogoPath,topicName,topicDesc,Integer.valueOf(topicCollectCount),Integer.valueOf(topicFavourCount));
                            topicList.add(addTopic);
                        }
                    }//end for
                    //设置空表
                    if(jsonArray.length()==0){}//searchListView.setEmptyView(findViewById(R.id.));}
                    else {
                        resultAdapter = new SearchResultAdapter(topicList, R.layout.topic_listview);
                        searchListView.setAdapter(resultAdapter);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onStart() {

            }
            @Override
            public void onFinish() {

            }
            @Override
            public void onFailure(int i, String s, Throwable throwable) {
                showToast(SearchResultActivity.this,"服务器连接失败");
            }
        });

        returnBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SearchResultActivity.this.finish();
            }
        });
    }//end onCreate
    class SearchResultAdapter extends BaseAdapter {
        int ResId;//单个Item布局
        List<Topic>topicList = new ArrayList<>();
        Topic theTopic;
        public SearchResultAdapter(List<Topic>theTopicList, int theResID){
            ResId = theResID; topicList = theTopicList;
        }
        /**
         * 各控件的引用
         */
        CircleImageView topicImageView;
        TextView catagory;
        TextView topicName;
        TextView topicReplyContent;
        TextView replyLikeCount;
        TextView replyCommentCount;
        /**
         *  content catagory topicName的引用 用来高亮搜索文字
         */
        String highLightCatagory,highLightTopicName,highLightComment;

        @Override
        public int getCount(){
            return topicList.size();
        }
        @Override
        public Object getItem(int position){
            return topicList.get(position);
        }
        @Override
        public long getItemId(int position){
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent){
            View view = LayoutInflater.from(SearchResultActivity.this).inflate(ResId, null);
            theTopic = (Topic)getItem(position);
            //获取每个View的各个控件的引用
            //Theme的Logo
            topicImageView = (CircleImageView) view.findViewById(R.id.topicImageView);
            //Theme的类别
            catagory = (TextView) view.findViewById(R.id.topicCatagory);
            //问题名字
            topicName = (TextView) view.findViewById(R.id.topicName);
            //问题的内容
            topicReplyContent = (TextView) view.findViewById(R.id.topicContent);
            //点赞数目
            replyLikeCount = (TextView) view.findViewById(R.id.topicAgreeNumber);
            //回复数目
            replyCommentCount = (TextView) view.findViewById(R.id.topicCommentNumber);

            SpannableString highLightCatagory = new SpannableString(theTopic.getTopicCatagory());
            SpannableString highLightTopicName = new SpannableString(theTopic.getTopicName());
            SpannableString highLightComment=null;
            if(theTopic.getaTopicReply()!=null) {
                highLightComment = new SpannableString(theTopic.getaTopicReply().getReplyContent());
            }
            Pattern p = Pattern.compile(searchKey);
            Matcher m = p.matcher(highLightCatagory);
            while (m.find()) {
                int start = m.start();
                int end = m.end();
                highLightCatagory.setSpan(new ForegroundColorSpan(Color.RED), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            m = p.matcher(highLightTopicName);
            while (m.find()) {
                int start = m.start();
                int end = m.end();
                highLightTopicName.setSpan(new ForegroundColorSpan(Color.RED), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            if(highLightComment!=null){
                m = p.matcher(highLightComment);
                while (m.find()){
                    int start = m.start(); int end = m.end();
                    highLightComment.setSpan(new ForegroundColorSpan(Color.RED),start,end,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            }
            /**
             * 设置话题Logo 待实现↓theTopic.getCatagoryLogoPath();
             */
            //String url = "http://192.168.191.1/Reading/ImageDoServlet?Action=download&Category=CategoryImage&ImageName="+ ThemeNameToLogo.getLogo(theTopic.getTopicCatagory());
            //abImageLoader.display(topicImageView,url,300,300);
            topicImageView.setImageResource(ThemeNameToLogo.getLogo(theTopic.getTopicCatagory()));

            catagory.setText(highLightCatagory);
            topicName.setText(highLightTopicName);

            if(theTopic.getaTopicReply()!=null) {
                topicReplyContent.setText(highLightComment);
                replyLikeCount.setText("点赞数:"+theTopic.getaTopicReply().getFavoCount());
                replyCommentCount.setText("评论数："+theTopic.getaTopicReply().getReplyCount());
            }
            else {
                topicReplyContent.setVisibility(View.GONE);
                replyLikeCount.setVisibility(View.GONE);
                replyCommentCount.setVisibility(View.GONE);
            }
            catagory.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(SearchResultActivity.this, ThemeActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("themeName",catagory.getText().toString());
                    intent.putExtras(bundle);
                    SearchResultActivity.this.startActivity(intent);
                }
            });
            topicName.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(SearchResultActivity.this,TopicWithReplyActivity.class);
                    intent.putExtra("topicObjWithReply",theTopic);
                    SearchResultActivity.this.startActivity(intent);
                }
            });
            topicReplyContent.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(SearchResultActivity.this,TopicActivity.class);
                    intent.putExtra("topicReplyObj",theTopic);
                    SearchResultActivity.this.startActivity(intent);
                }
            });
            return view;
        }//end method


    }//end adapter class
}
